package org.core.tliaswebmanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.core.tliaswebmanagement.mapper.EmpExprMapper;
import org.core.tliaswebmanagement.mapper.EmpMapper;
import org.core.tliaswebmanagement.pojo.*;
import org.core.tliaswebmanagement.service.EmpLogService;
import org.core.tliaswebmanagement.service.EmpService;
import org.core.tliaswebmanagement.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {

    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService  empLogService;

    // 原始分页查询
//    @Override
//    public PageResult<Emp> page(Integer page, Integer pageSize) {
//        Long total = empMapper.count();
//        Integer start = (page - 1) * pageSize;
//        List<Emp> rows = empMapper.list(start, pageSize);
//        return new PageResult<Emp>(total, rows);
//    }

//    @Override
//    public PageResult<Emp> page(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {
//        PageHelper.startPage(page, pageSize);//仅对其后的第一个查询有效
//        List<Emp> empslist = empMapper.list(name, gender, begin, end);
//        Page<Emp> pageInfo = (Page<Emp>) empslist;
//        return new PageResult<Emp>(pageInfo.getTotal(), pageInfo.getResult());
//    }

    @Override
    public PageResult<Emp> page(EmpQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Emp> empslist = empMapper.list(param);
        Page<Emp> pageInfo = (Page<Emp>) empslist;
        return new PageResult<Emp>(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Transactional(rollbackFor = {Exception.class}) //默认仅运行时异常才回滚事务
    @Override
    public void save(Emp emp) {
        try {
            log.info("新增员工信息：{}", emp);
            empMapper.insert(emp);
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach(expr -> expr.setEmpId(emp.getId()));
                empExprMapper.insertBatch(exprList);
            }
        } finally {
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "新增员工：" + emp);
            empLogService.insertLog(empLog);
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(List<Integer> ids) {
        empMapper.deleteByIds(ids);
        empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public Emp getInfo(Integer id) {
        return empMapper.getById(id);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);

        empExprMapper.deleteByEmpIds(List.of(emp.getId()));
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp e = empMapper.selectByUsernameAndPassword(emp);
        if (e != null) {
            //  生成JWT令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("username", e.getUsername());
            String token = JwtUtils.generateJwt(claims);
            LoginInfo info = new LoginInfo(e.getId(), e.getUsername(), e.getName(), token);
            return info;
        }
        return null;
    }

    @Override
    public List<Emp> findAll() {
        return empMapper.findAll();
    }
}
